﻿package com.hirokimo.display
{

	import com.hirokimo.event.SmartStageEvent;
	
	import flash.display.Stage;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
    /**  
    * 当舞台尺寸发生改变时发送事件  
    * @eventType com.hirokimo.event.SmartStageEvent.CHANGE_SIZE  
    */  
    [Event(name="change_size", type="com.hirokimo.event.SmartStageEvent")]

	/**
	 * SmartStage 自动设置舞台缩放模式,设置舞台事件侦听
	 * 
	 * @author	hirokimo
	 * 
	 * @example
	 * 
	 * 			<listing version="3.0">
	 *				var smartStage:SmartStage = SmartStage.getInstance(stage);
	 *				smartStage.addEventListener(SmartStageEvent.CHANGE_SIZE,__onSmartStageSizeChange);
	 * 			
	 * 			function __onSmartStageSizeChange(evt:SmartStageEvent):void
	 * 			{
	 * 				trace("宽度:" + evt.args.width);
	 * 				trace("高度:" + evt.args.height);
	 * 			}
	 * 			</listing>
	 */		
	public class SmartStage extends EventDispatcher
	{
		private static var key:Boolean = false;
		private static var stage:Stage;
		private static var instance:SmartStage;
		private static var width:int;
		private static var height:int;
		
		/**
		 * SmartStage 构造函数
		 * 
		 * @param _stage 初始化舞台对象,通常是继承于Sprite的文档类的引用.
		 */	
		public function SmartStage(_stage:Stage)
		{
			if(key)
			{
				//合法的初始化
				stage = _stage;
				width = stage.stageWidth;
				height = stage.stageHeight;			
				stage.scaleMode = StageScaleMode.NO_SCALE;    
				stage.align = StageAlign.TOP_LEFT;
				stage.addEventListener(Event.RESIZE,__onStageSizeChange);	
			}
			else
			{
				throw new Error("单例,请用 SmartStage.getInstance() 取实例。");
			}
		}
		/**
		 * SmartStage 单例取实例接口
		 * 
		 * @param _stage 初始化舞台对象,通常是继承于Sprite的文档类的this引用.
		 * @return SmartStage实例
		 */	
		public static function getInstance(_stage:Stage):SmartStage
		{
			if(instance == null)
			{
				key = true;
				instance = new SmartStage(_stage);
				key = false;
			}
			return instance;
		}
		/**
		 * 获得舞台宽度
		 * 
		 * @return 舞台宽度
		 */
		public function getWidth():int
		{
			return width;
		}
		/**
		 * 获得舞台高度
		 * 
		 * @return 舞台高度
		 */
		public function getHeight():int
		{
			return height;
		}
		private function __onStageSizeChange(evt:Event):void
		{
			height = stage.stageHeight;
			width = stage.stageWidth;
			var e:SmartStageEvent = new SmartStageEvent(SmartStageEvent.CHANGE_SIZE); 
			e.args = {width:width,height:height}; 
			dispatchEvent(e);
		}
	}
}